import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../layout/Home.vue'
import Login from '../views/Login'

import Dashboard from '../views/Dashboard'
// import Goods from '../views/Goods'
import Orders from '../views/Orders/index.vue'
// import Charts from '../views/Charts/index.vue'
// import Users from '../views/Users/index.vue'
// import Error from '../views/Error.vue'
import Mine from '../views/Mine/index.vue'
import _ from 'lodash'

// 解决了路由重复触发的报错
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location, onResolve, onReject) {
  if (onResolve || onReject) {
    return originalPush.call(this, location, onResolve, onReject)
  }
  return originalPush.call(this, location).catch((err) => err)
}

Vue.use(VueRouter)

const routes = [
  // 首页页面
  {
    path: '/',
    name: '首页页面',
    component: Home,
    children: [
      // 后台页面
      {
        path: '/',
        name: '后台页面',
        component: Dashboard
      }
      // // 商品管理
      // {
      //   path: '/goods',
      //   name: '商品管理',
      //   component: () =>
      //     import(/* webpackChunkName: "goods" */ '../views/Goods/index.vue'),
      //   children: [
      //     {
      //       path: '/goods/goodslist',
      //       name: '商品列表',
      //       component: () =>
      //         import(
      //           /* webpackChunkName: "goodslist" */ '../views/Goods/GoodsList.vue'
      //         )
      //     },
      //     {
      //       path: '/goods/goodsadd',
      //       name: '上传商品',
      //       component: () =>
      //         import(
      //           /* webpackChunkName: "goodsadd" */ '../views/Goods/GoodsAdd.vue'
      //         )
      //     },
      //     {
      //       path: '/goods/goodsedit/:id', // : 后面可以写 name 等
      //       name: '商品编辑',
      //       component: () =>
      //         import(
      //           /* webpackChunkName: "goodsadd" */ '../views/Goods/GoodsEdit.vue'
      //         )
      //     }
      //   ]
      // },
      // // 订单管理
      // {
      //   path: '/orders',
      //   name: '订单管理',
      //   component: Orders
      // },
      // // 可视化数据
      // {
      //   path: '/charts',
      //   name: '可视化数据',
      //   meta: { role: [1] },
      //   component: () =>
      //     import(/* webpackChunkName: "charts" */ '../views/Charts/index.vue'),
      //   children: [
      //     {
      //       path: '/charts/order',
      //       name: '订单数据',
      //       component: () =>
      //         import(
      //           /* webpackChunkName: "order" */ '../views/Charts/Order.vue'
      //         )
      //     },
      //     {
      //       path: '/charts/sellcount',
      //       name: '销量数据',
      //       component: () =>
      //         import(
      //           /* webpackChunkName: "sellcount" */ '../views/Charts/SellCount.vue'
      //         )
      //     }
      //   ]
      // },
      // // 用户管理
      // {
      //   path: '/users',
      //   name: '用户管理',
      //   meta: { role: [1] },
      //   component: () =>
      //     import(/* webpackChunkName: "users" */ '../views/Users/index.vue'),
      //   children: [
      //     {
      //       path: '/users/userslist',
      //       name: '账号列表',
      //       meta: { role: [1] },
      //       component: () =>
      //         import(
      //           /* webpackChunkName: "usersadd" */ '../views/Users/UsersList.vue'
      //         )
      //     },
      //     {
      //       path: '/users/usersadd',
      //       name: '添加账号',
      //       meta: { role: [1] },
      //       component: () =>
      //         import(
      //           /* webpackChunkName: "usersadd" */ '../views/Users/UsersAdd.vue'
      //         )
      //     },
      //     {
      //       path: '/users/resetpwd',
      //       name: '修改密码',
      //       meta: { role: [1, 2] },
      //       component: () =>
      //         import(
      //           /* webpackChunkName: "resetpwd" */ '../views/Users/ResetPwd.vue'
      //         )
      //     },
      //     // 个人中心
      //     {
      //       path: '/mine',
      //       name: '个人中心',
      //       meta: { role: [1, 2] },
      //       component: Mine
      //     }
      //   ]
      // }
    ]
  },
  // 登陆页面
  {
    path: '/login',
    name: '登陆页面',
    component: Login
  },
  // 报错页面
  {
    path: '*',
    name: '报错页面',
    redirect: '/404'
  },
  {
    path: '/404',
    name: '报错页面',
    component: () =>
      import(/* webpackChunkName: "error" */ '../views/Error.vue')
  }
]

// 提取静态路由
const AsyncRoutes =
  // 首页页面
  {
    path: '/',
    name: '首页页面',
    component: Home,
    children: [
      // 后台页面
      {
        path: '/',
        name: '后台页面',
        component: Dashboard
      },
      // 商品管理
      {
        path: '/goods',
        name: '商品管理',
        component: () =>
          import(/* webpackChunkName: "goods" */ '../views/Goods/index.vue'),
        children: [
          {
            path: '/goods/goodslist',
            name: '商品列表',
            component: () =>
              import(
                /* webpackChunkName: "goodslist" */ '../views/Goods/GoodsList.vue'
              )
          },
          {
            path: '/goods/goodsadd',
            name: '上传商品',
            component: () =>
              import(
                /* webpackChunkName: "goodsadd" */ '../views/Goods/GoodsAdd.vue'
              )
          },
          {
            path: '/goods/goodsedit/:id', // : 后面可以写 name 等
            name: '商品编辑',
            hidden: true,
            // visible:false
            component: () =>
              import(
                /* webpackChunkName: "goodsadd" */ '../views/Goods/GoodsEdit.vue'
              )
          }
        ]
      },
      // 订单管理
      {
        path: '/orders',
        name: '订单管理',
        component: Orders
      },
      // 可视化数据
      {
        path: '/charts',
        name: '可视化数据',
        meta: { role: [1] },
        component: () =>
          import(/* webpackChunkName: "charts" */ '../views/Charts/index.vue'),
        children: [
          {
            path: '/charts/order',
            name: '订单数据',
            component: () =>
              import(
                /* webpackChunkName: "order" */ '../views/Charts/Order.vue'
              )
          },
          {
            path: '/charts/sellcount',
            name: '销量数据',
            component: () =>
              import(
                /* webpackChunkName: "sellcount" */ '../views/Charts/SellCount.vue'
              )
          }
        ]
      },
      // 用户管理
      {
        path: '/users',
        name: '用户管理',
        meta: { role: [1, 2] },
        component: () =>
          import(/* webpackChunkName: "users" */ '../views/Users/index.vue'),
        children: [
          {
            path: '/users/userslist',
            name: '账号列表',
            meta: { role: [1] },
            component: () =>
              import(
                /* webpackChunkName: "usersadd" */ '../views/Users/UsersList.vue'
              )
          },
          {
            path: '/users/usersadd',
            name: '添加账号',
            meta: { role: [1] },
            component: () =>
              import(
                /* webpackChunkName: "usersadd" */ '../views/Users/UsersAdd.vue'
              )
          },
          {
            path: '/users/resetpwd',
            name: '修改密码',
            meta: { role: [1, 2] },
            component: () =>
              import(
                /* webpackChunkName: "resetpwd" */ '../views/Users/ResetPwd.vue'
              )
          },
          // 个人中心
          {
            path: '/mine',
            name: '个人中心',
            hidden: true,
            // visible:false
            meta: { role: [1, 2] },
            component: Mine
          }
        ]
      }
    ]
  }

// 创建一个函数, 根据用户权限计算新的路由
export function getNewRoutes() {
  // role - 1 超级管理员，2 普通管理员
  const role = JSON.parse(window.localStorage.getItem('users') || '{}').group_id
  if (!role) return
  const lastRoutes = filterRoutes(role, AsyncRoutes.children)
  // console.log(lastRoutes)

  // 路由虽然计算出来了，但是没有添加到主路由上
  // !!!核心语法 - router.addRoute() 添加对象  router.addRoutes() 添加数组
  AsyncRoutes.children = lastRoutes
  router.addRoute(AsyncRoutes)
  // router.addRoutes([AsyncRoutes])

  // 在已有的路由上，再次过滤需要展示在侧边栏上的路由，进行保存
  const menuArr = _.cloneDeep(lastRoutes)
  const newMenu = filterMenus(menuArr)
  // console.log(menuArr)
  localStorage.setItem('menu', JSON.stringify(newMenu))
}

function filterMenus(arr) {
  return arr.filter((item) => {
    if (item.hidden) {
      return false
    } else {
      if (item.children) {
        item.children = filterMenus(item.children)
      }
      return true
    }
  })
}

// 真正过滤数组的函数
function filterRoutes(n, arr) {
  // filter - 会把满足条件的项保留
  return arr.filter((item) => {
    if (item.meta && item.meta.role) {
      if (item.meta.role.includes(n)) {
        // 需要鉴定权限，如果有 children，最好再过滤一次
        if (item.children) {
          // 通过自身调用自身(递归的方式)把子路由也过滤出来
          item.children = filterRoutes(n, item.children)
        }
        return true
      } else {
        return false
      }
    } else {
      // 如果没有字段 meta，就会保留公共的路由(超级管理员和普通管理员都能看到)
      return true
    }
  })
}

const router = new VueRouter({
  routes
})

getNewRoutes()

// 路由页面添加以下代码：
// const originalPush = VueRouter.prototype.push
// VueRouter.prototype.push = function push(location) {
//   return originalPush.call(this, location).catch((err) => err)
// }

// 使用路由的导航守卫完成登录的拦截功能
router.beforeEach((to, from, next) => {
  // 根据登录之后保存的这个凭证能够知道是否登录
  const users = window.localStorage.getItem('users') || '{}'
  const token = JSON.parse(users).access_token
  if (token) {
    next()
  } else {
    if (to.path === '/login') {
      next()
    } else {
      next('/login')
    }
  }
})

export default router
